package models;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;

import entities.KeywordRanking;

public class KeywordRankingModel {
	private Objectify ofy;
	
	private String prefix = "keyword_ranking_";
	
	private static KeywordRankingModel instance = null;
	
	public static KeywordRankingModel getInstance() {
		if (instance == null) {
			instance = new KeywordRankingModel();
		}
		
		return instance;
	}
	
	private KeywordRankingModel() {
		try {
			ObjectifyService.register(KeywordRanking.class);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
        ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}
	
	public KeywordRanking get(String domainName) {
		KeywordRanking keyword = new KeywordRanking();
		try {
			keyword = ofy.get(new Key<KeywordRanking>(KeywordRanking.class, domainName));
		} catch (Exception e) {
			keyword = null;
		}
		
		return keyword;
	}
	
	public void insert(KeywordRanking keyword) {
		ofy.put(keyword);
	}
	
	public void delete(KeywordRanking keyword) {
		ofy.delete(keyword);
	}

	public List<KeywordRanking> getByListId(List<String> ids) {
		List<KeywordRanking> keywords = new ArrayList<KeywordRanking>();
		KeywordRanking keyword = null;
		for (int i = 0; i < ids.size(); i++) {
			keyword = get(ids.get(i));
			if (keyword != null) {
				keywords.add(keyword);
			}
		}
		
		return keywords;
	}
	
}
